package com.ody.util.code.model;

import com.google.common.collect.Lists;
import org.springframework.util.AntPathMatcher;
import org.springframework.util.Assert;

import java.util.List;

public class PatternParser {
    private boolean matchAll;
    private List<String> publicPatterns;
    private List<String> includePatterns;
    private List<String> excludePatterns;
    
    private AntPathMatcher matcher = new AntPathMatcher();
    
    public PatternParser(String pattern, String name) {
        Assert.hasText(pattern, name + " pattern is required");
        String[] items = pattern.split("[,]");
        includePatterns = Lists.newArrayList();
        excludePatterns = Lists.newArrayList();
        publicPatterns = Lists.newArrayList();
        for (String item : items) {
            item = item.trim();
            if ("*".equals(item)) {
                matchAll = true;
            } else if (item.startsWith("-")) {
                excludePatterns.add(item.substring(1));
            } else if (item.startsWith("+")) {
                addPattern(item.substring(1));
            } else if (item.startsWith("#")) {
                publicPatterns.add(item.substring(1));
            } else {
                addPattern(item);
            }
        }
    }
    
    public boolean isMatches(String item) {
        for (String pattern : excludePatterns) {
            if (matcher.match(pattern, item)) return false;
        }
        for (String pattern : includePatterns) {
            if (matcher.match(pattern, item)) return true;
        }
        
        return matchAll;
    }
    
    public boolean isPublic(String item) {
        for (String pattern : publicPatterns) {
            if (matcher.match(pattern, item)) {
                return true;
            }
        }
        return false;
    }
    
    protected void addPattern(String pattern) {
        if (!includePatterns.contains(pattern)) {
            includePatterns.add(pattern);
        }
    }
}
